<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: allen.qiang
// +----------------------------------------------------------------------

/**
 * 商品限时特价类
 * @package  module
 * @subpackage  base/system
 * @author   allen.qiang
 * @version 1.0
 */

class goodsSpecial {

    private $dbca;

    public function __construct( $dbca ) {
        $this->dbca = $dbca;
    }

    /**
     * 查询特价活动列表
     * @param $arg_array
     * @return array|null
     */
    public function searchGoodsSpecialList(&$arg_array){
        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //活动ID
        if (isset($arg_array['promotionID']) && is_numeric($arg_array['promotionID'])) {
            $sql .= ' AND promotionID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['promotionID'];
        }

        //网购号
        if (isset($arg_array['postID']) && is_numeric($arg_array['postID'])) {
            $sql .= ' AND postID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['postID'];
        }

        //商品编号
        if (isset($arg_array['product_code']) && !empty($arg_array['product_code'])) {
            $sql .= ' AND product_code = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['product_code'];
        }

        //商品名称
        if (isset($arg_array['goodsName']) &&  !empty($arg_array['goodsName']) ) {
            $sql .= ' AND goodsName like ?';
            $params_type .= 's';
            $params_array[] = '%'.$arg_array['goodsName'].'%';
        }

        //开始日期
        if (isset($arg_array['startDate']) && !empty($arg_array['startDate']) ) {
            $sql .= ' AND startDate >= ?';
            $params_type .= 's';
            $params_array[] = $arg_array['startDate'];
        }

        if (isset($arg_array['endDate']) &&  !empty($arg_array['endDate']) ) {
            $sql .= ' AND endDate <= ?';
            $params_type .= 's';
            $params_array[] = $arg_array['endDate'];
        }

        if (isset($arg_array['currentDate']) &&  !empty($arg_array['currentDate']) ) {
            $sql .= ' AND startDate <= ? AND endDate >= ?';
            $params_type .= 'ss';
            $params_array[] = $arg_array['currentDate'];
            $params_array[] = $arg_array['currentDate'];
        }

        //状态 0:禁用 1:启用
        if (isset($arg_array['useFlg']) && in_array($arg_array['useFlg'], array(0 ,1))) {
            $sql .= ' AND useFlg = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['useFlg'];
        }

        //扩展查询
        if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
            $sql .= $arg_array['extend'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计分类数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM promotion_special ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                $arg_array['count'] = 0;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM promotion_special ' . $sql;

            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'createTime' => $item->createTime,
                    'creator' => $item->creator,
                    'promotionID' => $item->promotionID,
                    'goodsName' => $item->goodsName,
                    'postID' => $item->postID,
                    'goodsID' => $item->goodsID,
                    'product_code' => $item->product_code,
                    'salePrice' => $item->salePrice,
                    'specialPrice' => $item->specialPrice,
                    'spec' => $item->spec,
                    'startDate' => $item->startDate,
                    'endDate' => $item->endDate,
                    'startTime' => $item->startTime,
                    'rebuyNum' => $item->rebuyNum,
                    'useFlg' => $item->useFlg

                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }


    /**
     * 查询今日特价会员购买记录
     * @param $arg_array
     * @return array|null
     */
    public function searchGoodsSpecialLog(&$arg_array){

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //用户号
        if (isset($arg_array['pcustID']) && is_numeric($arg_array['pcustID'])) {
            $sql .= ' AND pcustID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['pcustID'];
        }

        //活动号
        if (isset($arg_array['promotionID']) && !empty($arg_array['promotionID'])) {
            $sql .= ' AND promotionID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['promotionID'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计分类数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM promotion_special_log ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                $arg_array['count'] = 0;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM promotion_special_log ' . $sql;

            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(

                    'createTime' 	=> $item->createTime,
                    'creator' 		=> $item->creator,
                    'goods_amount'  => $item->goods_amount,
                    'pcustID' 	    => $item->pcustID,
                    'promotionID' 	=> $item->promotionID
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 特价活动启用禁用
     * @param $arg_array
     * @return array|null
     */
    public function useSpecialAction(&$arg_array){
        if(!isset($arg_array['promotionID']) || !isset($arg_array['useFlg'])){
            return array('code'=>400,'message'=>'参数错误');
        }

        try{

            $promotion_special = new entity('promotion_special');
            $promotion_special->promotionID = $arg_array['promotionID'];
            if($this->dbca->fetch($promotion_special)){

                $promotion_special->useFlg = $arg_array['useFlg'];
                $this->dbca->save($promotion_special);

            }else{
                return array('code'=>400,'message'=>'特价不存在');
            }

            if($arg_array['useFlg'] == 1){
                return array('code'=>200,'message'=>'特价活动启用成功');
            }else{
                return array('code'=>200,'message'=>'特价活动禁用成功');
            }

        }catch(Exception $e){
            error_log($e->getMessage());
            return null;
        }
    }

    /**
     * 特价活动保存
     * @param $arg_array
     * @return array|null
     */
    public function goodsSpecialSave(&$arg_array){

        //公共类
        $commHandler = new commHandler($this->dbca);

        //商品编号
        if(!isset($arg_array['product_code']) || empty($arg_array['product_code'])){
            return array('code'=>400,'message'=>'特价商品编号不能为空');
        }

        //商品名称
        if(!isset($arg_array['specialPrice']) || empty($arg_array['specialPrice'])){
            return array('code'=>400,'message'=>'商品特价不能为空');
        }

        //开始日期
        if(!isset($arg_array['startDate']) || empty($arg_array['startDate'])){
            return array('code'=>400,'message'=>'开始日期不能为空');
        }

        //结束日期
        if(!isset($arg_array['endDate']) || empty($arg_array['endDate'])){
            return array('code'=>400,'message'=>'结束日期不能为空');
        }

        //可购数量
        if(!isset($arg_array['rebuyNum']) || empty($arg_array['rebuyNum'])){
            return array('code'=>400,'message'=>'限购数量不能为空');
        }



        try{

            $num = 0;
            $promotion_special = $this->dbca->stmt_query('select count(*) as num from promotion_special where startDate >= ? and startDate <= ? and useFlg = ?  ','ssi',array($arg_array['startDate'],$arg_array['endDate'],1));
            $num += $promotion_special[0]->num;
            $promotion_special_checkone = $this->dbca->stmt_query('select count(*) as num from promotion_special where startDate<=? and endDate >=? and useFlg = ?  ','ssi',array($arg_array['startDate'],$arg_array['startDate'],1));
            $num += $promotion_special_checkone[0]->num;

            if($num>0){
                return array('code'=>400,'message'=>'在 ['.$arg_array['startDate'].' ~ '.$arg_array['endDate'].'] 时间段内有重复特价活动');
            }

            //实例化商品类
            $goodsHandler = new goodsHandler( $this->dbca );

            //查询商品信息
            $goods_arg_array = array(
                'product_code' => $arg_array['product_code'],
                'useFlg' => 1,
                'forsale' => 1
            );
            $goods_array = $goodsHandler->searchGoodsSale( $goods_arg_array );

            if (!$goods_array){
                return array('code'=>400,'message'=>'商品信息没有找到');
            }

            $promotionID = $commHandler->generate_seqno('seqno_promotion');//获取自增活动ID

            $promotion_special = new entity('promotion_special');
            $promotion_special->creator = $arg_array['creator'];
            $promotion_special->promotionID = $promotionID;
            $promotion_special->goodsName = $goods_array['goodsName'];
            $promotion_special->postID = $goods_array['postID'];
            $promotion_special->goodsID = $goods_array['goodsID'];
            $promotion_special->product_code = $goods_array['product_code'];
            $promotion_special->salePrice = $goods_array['salePrice'];
            $promotion_special->specialPrice = $arg_array['specialPrice'];
            $promotion_special->spec = $goods_array['spec'];
            $promotion_special->startDate = $arg_array['startDate'];
            $promotion_special->endDate = $arg_array['endDate'];
            $promotion_special->rebuyNum = $arg_array['rebuyNum'];
            $promotion_special->useFlg = 1; //默认状态下使用
            $this->dbca->save($promotion_special);

            return array('code'=>200,'message'=>'保存成功');

        }catch(Exception $e){
            error_log($e->getMessage());
            return null;
        }

    }

    /**
     * 特价活动编辑
     * @param $arg_array
     * @return array|null
     */
    public function goodsSpecialEdit(&$arg_array){

        //公共类
        $commHandler = new commHandler($this->dbca);

        //商品编号
        if(!isset($arg_array['product_code']) || empty($arg_array['product_code'])){
            return array('code'=>400,'message'=>'特价商品编号不能为空');
        }

        //特价价格
        if(!isset($arg_array['specialPrice']) || empty($arg_array['specialPrice'])){
            return array('code'=>400,'message'=>'商品特价不能为空');
        }

        //开始日期
        if(!isset($arg_array['startDate']) || empty($arg_array['startDate'])){
            return array('code'=>400,'message'=>'开始日期不能为空');
        }

        //结束日期
        if(!isset($arg_array['endDate']) || empty($arg_array['endDate'])){
            return array('code'=>400,'message'=>'结束日期不能为空');
        }

        //可购数量
        if(!isset($arg_array['rebuyNum']) || empty($arg_array['rebuyNum'])){
            return array('code'=>400,'message'=>'限购数量不能为空');
        }

        try{

            $num = 0;
            $promotion_special = $this->dbca->stmt_query('select count(*) as num from promotion_special where startDate >= ? and startDate <= ? and useFlg = ? and promotionID != ?  ','ssii',array($arg_array['startDate'],$arg_array['endDate'],1,$arg_array['promotionID']));
            $num += $promotion_special[0]->num;
            $promotion_special_checkone = $this->dbca->stmt_query('select count(*) as num from promotion_special where startDate<=? and endDate >=? and useFlg = ? and promotionID != ?   ','ssii',array($arg_array['startDate'],$arg_array['startDate'],1,$arg_array['promotionID']));
            $num += $promotion_special_checkone[0]->num;

            if($num>0){
                return array('code'=>400,'message'=>'在 ['.$arg_array['startDate'].' ~ '.$arg_array['endDate'].'] 时间段内有重复特价活动');
            }

            //实例化商品类
            $goodsHandler = new goodsHandler( $this->dbca );

            //查询商品信息
            $goods_arg_array = array(
                'product_code' => $arg_array['product_code'],
                'useFlg' => 1,
                'forsale' => 1
            );
            $goods_array = $goodsHandler->searchGoodsSale( $goods_arg_array );

            if (!$goods_array){
                return array('code'=>400,'message'=>'商品信息没有找到');
            }

            $promotion_special = new entity('promotion_special');
            $promotion_special->promotionID = $arg_array['promotionID'];

            if($this->dbca->fetch($promotion_special)){

                $promotion_special->creator = $arg_array['creator'];
                $promotion_special->goodsName = $goods_array['goodsName'];
                $promotion_special->postID = $goods_array['postID'];
                $promotion_special->goodsID = $goods_array['goodsID'];
                $promotion_special->product_code = $goods_array['product_code'];
                $promotion_special->salePrice = $goods_array['salePrice'];
                $promotion_special->specialPrice = $arg_array['specialPrice'];
                $promotion_special->spec = $goods_array['spec'];
                $promotion_special->startDate = $arg_array['startDate'];
                $promotion_special->endDate = $arg_array['endDate'];
                $promotion_special->rebuyNum = $arg_array['rebuyNum'];

                $this->dbca->save($promotion_special);

            }else{
                return array('code'=>400,'message'=>'该特价活动不存在');
            }

            return array('code'=>200,'message'=>'保存成功');

        }catch (Exception $e){
            error_log($e->getMessage());
            return null;
        }

    }

    /**
     * 特价活动删除
     * @param $arg_array
     * @return array|null
     */
    public function goodsSpecialDelete(&$arg_array){

        if(!isset($arg_array['pid'])){
            return array('code'=>400,'message'=>'参数错误');
        }

        try{

            foreach($arg_array['pid'] as $val){
                $this->dbca->stmt_query('DELETE FROM promotion_special WHERE promotionID = ?','i',$val);
            }

            return array('code'=>200,'message'=>'删除成功');

        }catch(Exception $e){

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 新增或更新限时特价会员购买记录
     * @param $promotionID int 活动号
     * @param $pcustID int 会员号
     * @param $goods_amount int 商品数量
     */
    public function updateSpecialLog($promotionID, $pcustID, $goods_amount){

        $promotion_special_log = new entity('promotion_special_log');
        $promotion_special_log->pcustID = $pcustID;
        $promotion_special_log->promotionID = $promotionID;
        if ($this->dbca->fetch($promotion_special_log)) {
            $promotion_special_log->goods_amount += $goods_amount;
        } else {
            $promotion_special_log->creator = 'system';
            $promotion_special_log->goods_amount = $goods_amount;
        }
        $this->dbca->save($promotion_special_log);

    }

}